package com.xlisteven.springboot_ssm_tkmapper.controller;

import com.xlisteven.springboot_ssm_tkmapper.bean.User;
import com.xlisteven.springboot_ssm_tkmapper.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/")
    public String findAllUser(Model model) {
        List<User> userList = userService.findAllUser();
        model.addAttribute("userList", userList);
        return "index";
    }

    @RequestMapping("/toEdit")
    public String toEdit(Integer id, Model model) {
        User user = userService.findUserById(id);
        if (user != null) {
            model.addAttribute("user", user);
            return "userEdit";
        }
        return null;
    }

    @RequestMapping("/edit")
    public String edit(User user) {
        userService.updateUser(user);
        return "redirect:/";
    }

    @RequestMapping("/delete")
    public String delete(Integer id) {
        userService.deleteUserById(id);
        return "redirect:/";
    }

    @RequestMapping("/toAdd")
    public String toAdd() {
        return "userAdd";
    }

    @RequestMapping("/add")
    public String add(User user) {
        int result = userService.saveUser(user);
        if (result > 0) {
            return "redirect:/";
        }
        return null;
    }

    @RequestMapping("search")
    public String search(String name,Model model) {
        List<User> userList = userService.search(name);
        if (userList != null) {
            model.addAttribute("userList", userList);
            return "index";
        }
        return null;
    }
}
